/**
 * 手动任务脚本
 * 更新当前用户客户，只更新当前客户下的客户列表信息
 * @param {string} corpid 企业微信 corpid 或 appid
 * @param {string} corpsecret 企业微信 secret
 */
(function (corpid, corpsecret) {
  var applicationId = $.context.getCurrentApplicationId();
  var currentUser = $.context.getCurrentUser();
  var userId = currentUser.getWxUserId();
  var formName = "企微添加客户";
  var conditionMap = new Packages.java.util.HashMap();
  conditionMap.put("员工", userId);
  var customerList = $.form.getDocumentsByCondition(
    applicationId,
    formName,
    conditionMap
  );
  var customerIds = [];
  if (customerList.size() > 0) {
    for (var i = 0; i < customerList.size(); i++) {
      var id = customerList.get(i).getElementByName("客户").getValue();
      customerIds.push(String(id));
    }
  }

  // 开始同步企业微信客户
  // 获取token
  var tokenUri = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
  var tokenParams = new Packages.java.util.HashMap();
  var tokenHeader = new Packages.java.util.HashMap();
  tokenParams.put("corpid", corpid);
  tokenParams.put("corpsecret", corpsecret);
  var acceccRes = $.httpclient.sendGet(tokenUri, tokenParams, tokenHeader);
  var accessToken = JSON.parse(acceccRes).access_token;
  // 更新状态表当前用户的同步状态为“同步中”
  var conditions = new Packages.java.util.HashMap();
  conditions.put("员工id", userId);
  var documents = $.form.getDocumentsByCondition(
    applicationId,
    "员工客户同步状态",
    conditions
  );
  var document = null;
  if (documents.size() > 0) {
    document = documents.get(0);
    document.addElement("同步状态", "2");
    $.form.saveFormDocument(document, applicationId);
  }

  getExternalContact();
  // 从企业微信获取客户列表
  function getExternalContact(cursor) {
    //var userId = currentUser.getWxUserId();
    cursor = cursor || "";
    // 获取企业微信客户
    var uri = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user";
    var params = new Packages.java.util.HashMap();
    var headers = new Packages.java.util.HashMap();
    var json = {
      userid: userId,
      cursor: cursor,
      limit: 100,
    };
    var genderMap = ["3", "1", "2"];
    var jsonStr = $.json.objectToJsonString(json);
    headers.put("Content-Type", "application/json;charset=UTF-8");
    params.put("access_token", accessToken);
    var response = $.httpclient.sendPost(uri, params, headers, jsonStr);
    var resData = $.json.stringToJsonObject(response);
    var nextCursor = resData.get("next_cursor");
    // 循环塞数据
    var list = resData.get("external_contact_list");
    if (list.size()) {
      for (var i = 0; i < list.size(); i++) {
        var item = list.get(i);
        var follow = item.get("follow_info");
        var external = item.get("external_contact");
        var timestamp = follow.get("createtime") * 1000;
        var doc = $.form.createEmptyDocument(applicationId, "企微添加客户");
        // 如果已经有这个客户，直接覆盖原来的数据
        var extId = String(external.get("external_userid"));
        if (customerIds.indexOf(extId) > -1) {
          doc = customerList.get(customerIds.indexOf(extId));
        }
        var mobileStr = "";
        for (var j = 0; j < follow.get("remark_mobiles").size(); j++) {
          mobileStr += follow.get("remark_mobiles").get(j) + ",";
        }
        doc.addElement("客户", external.get("external_userid"));
        doc.addElement("企微", external.get("unionid"));
        doc.addElement("员工", follow.get("userid"));
        doc.addElement("姓名", external.get("name"));
        doc.addElement("类型", external.get("type"));
        doc.addElement("性别", genderMap[external.get("gender")]);
        doc.addElement("职位", external.get("position"));
        doc.addElement("企业简称", external.get("corp_name"));
        doc.addElement("企业全称", external.get("corp_full_name"));
        doc.addElement("添加时间", timestamp);
        doc.addElement("备注", follow.get("remark"));
        doc.addElement("客户电话", mobileStr.slice(0, -1));
        doc.addElement("同步状态", "1");
        $.form.saveFormDocument(doc, applicationId);
      }
    }
    if (nextCursor != "" && nextCursor != "undefined") {
      getExternalContact(nextCursor);
    } else {
      // 同步完成，修改状态
      if (document != null) {
        document.addElement("同步状态", "3");
        $.form.saveFormDocument(document, applicationId);
      }
    }
  }
})("ww36614f2eb0f9d781", "8hcHPnLQNFnosu5IcfENXKxmet73LRMY8epi-GvXXmI");
